
import 'dart:math';
import '../models/pregnancy_model.dart';
import '../services/database_helper.dart';

class PregnancyService {
  final DatabaseHelper? _dbHelper;
  
  PregnancyService([this._dbHelper]);

  // 初始化孕期信息
  Future<PregnancyInfo> initializePregnancy({
    required int userId,
    required DateTime lastPeriodDate,
    DateTime? confirmedPregnancyDate,
    String? conceptionMethod,
    String? pregnancyType,
    String? notes,
  }) async {
    // 计算预产期
    final dueDate = lastPeriodDate.add(Duration(days: 280));
    
    // 更新当前孕周
    final now = DateTime.now();
    final daysSinceLMP = now.difference(lastPeriodDate).inDays;
    final currentWeek = (daysSinceLMP / 7).floor();
    final currentDay = daysSinceLMP % 7;

    final pregnancyInfo = PregnancyInfo(
      userId: userId,
      lastPeriodDate: lastPeriodDate,
      estimatedDueDate: dueDate,
      confirmedPregnancyDate: confirmedPregnancyDate,
      pregnancyStatus: 'ongoing',
      conceptionMethod: conceptionMethod,
      currentWeek: currentWeek,
      currentDay: currentDay,
      pregnancyType: pregnancyType ?? 'singleton',
      notes: notes,
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
    );

    // 保存到数据库
    final id = await _dbHelper?.insert('pregnancy_info', pregnancyInfo.toMap());
    
    // 加载默认的胎儿发育数据
    await _loadDefaultFetalDevelopmentData();
    
    // 加载默认的食物安全数据
    await _loadDefaultFoodSafetyData();
    
    // 加载默认的孕期里程碑
    await _loadDefaultMilestones();
    
    return pregnancyInfo.copyWith(id: id);
  }

  // 更新孕期信息
  Future<PregnancyInfo> updatePregnancyInfo({
    required int id,
    DateTime? lastPeriodDate,
    DateTime? estimatedDueDate,
    String? pregnancyStatus,
    String? notes,
  }) async {
    // 获取现有信息
    if (_dbHelper == null) {
      throw Exception('数据库未初始化');
    }
    final results = await _dbHelper!.queryRows('pregnancy_info', where: {'id': id});
    if (results.isEmpty) {
      throw Exception('孕期信息不存在');
    }
    final existingInfo = results.first;

    // 更新信息
    final updatedInfo = PregnancyInfo.fromMap(existingInfo).copyWith(
      lastPeriodDate: lastPeriodDate ?? PregnancyInfo.fromMap(existingInfo).lastPeriodDate,
      estimatedDueDate: estimatedDueDate ?? PregnancyInfo.fromMap(existingInfo).estimatedDueDate,
      pregnancyStatus: pregnancyStatus ?? PregnancyInfo.fromMap(existingInfo).pregnancyStatus,
      notes: notes ?? PregnancyInfo.fromMap(existingInfo).notes,
      updatedAt: DateTime.now(),
    );

    // 更新当前孕周
    updatedInfo.updateCurrentWeek();

    // 保存到数据库
      final updateData = updatedInfo.toMap();
      await _dbHelper?.update('pregnancy_info', updateData, id);
    
    return updatedInfo;
  }

  // 获取用户的孕期信息
    Future<PregnancyInfo?> getPregnancyInfo(int userId) async {
      if (_dbHelper == null) return null;
      
      final results = await _dbHelper!.queryRows('pregnancy_info', where: {DatabaseHelper.columnUserId: userId});
      if (results.isNotEmpty) {
        final info = PregnancyInfo.fromMap(results.first);
        // 更新当前孕周
        info.updateCurrentWeek();
        // 更新数据库
          if (info.id != null) {
            final updateData = info.toMap();
            await _dbHelper!.update('pregnancy_info', updateData, info.id!);
          }
        return info;
      }
      return null;
    }

  // 获取当前孕周的胎儿发育信息
  Future<FetalDevelopment?> getCurrentFetalDevelopment(int week) async {
    try {
      if (_dbHelper != null) {
        // 使用通用查询方法替代未定义的getFetalDevelopmentByWeek方法
        final results = await _dbHelper!.queryRows('fetal_development', where: {'week': week});
        if (results.isNotEmpty) {
          return FetalDevelopment.fromMap(results.first);
        }
      }
    } catch (e) {
      // 记录错误但不使用print
    }
    
    // 如果数据库中没有，生成一个默认的
    return _generateDefaultFetalDevelopment(week);
  }

  // 获取未来几周的胎儿发育预测
  Future<List<FetalDevelopment>> getFutureFetalDevelopment(
      int currentWeek, int weeksAhead) async {
    final developments = <FetalDevelopment>[];
    
    for (int i = 1; i <= weeksAhead; i++) {
      final week = currentWeek + i;
      if (week <= 40) { // 限制到预产期
        final development = await getCurrentFetalDevelopment(week);
        if (development != null) {
          developments.add(development);
        }
      }
    }
    
    return developments;
  }

  // 记录产检
  Future<PrenatalVisit> recordPrenatalVisit({
    required int userId,
    required DateTime visitDate,
    required int weekOfPregnancy,
    required String doctorName,
    required String hospitalName,
    required String visitType,
    String? bloodPressure,
    double? weight,
    double? fundalHeight,
    int? fetalHeartRate,
    String? urineTestResults,
    String? bloodTestResults,
    String? ultrasoundResults,
    String? nextVisitDate,
    String? doctorNotes,
    String? motherNotes,
    List<String>? medications,
    List<String>? prescribedTests,
  }) async {
    final visit = PrenatalVisit(
      userId: userId,
      visitDate: visitDate,
      weekOfPregnancy: weekOfPregnancy,
      doctorName: doctorName,
      hospitalName: hospitalName,
      visitType: visitType,
      bloodPressure: bloodPressure,
      weight: weight,
      fundalHeight: fundalHeight,
      fetalHeartRate: fetalHeartRate,
      urineTestResults: urineTestResults,
      bloodTestResults: bloodTestResults,
      ultrasoundResults: ultrasoundResults,
      nextVisitDate: nextVisitDate,
      doctorNotes: doctorNotes,
      motherNotes: motherNotes,
      medications: medications,
      prescribedTests: prescribedTests,
    );

    final id = await _dbHelper?.insert('prenatal_visits', visit.toMap());
    
    // 如果有下次产检日期，创建提醒
    // if (nextVisitDate != null) {
    //   final nextDate = DateTime.tryParse(nextVisitDate);
    //   if (nextDate != null) {
    //     // await _createNextVisitReminder(userId, nextDate, doctorName, hospitalName);
    //   }
    // }
    
    return visit.copyWith(id: id);
  }

  // 获取产检历史
  Future<List<PrenatalVisit>> getPrenatalVisits(int userId) async {
    try {
      if (_dbHelper != null) {
        // 使用通用查询方法替代未定义的getPrenatalVisits方法
        final results = await _dbHelper!.queryRows('prenatal_visits', where: {'user_id': userId});
        return results.map((map) => PrenatalVisit.fromMap(map)).toList();
      }
    } catch (e) {
      // 记录错误但不使用print
    }
    return [];
  }

  // 获取下次产检信息
  Future<PrenatalVisit?> getNextPrenatalVisit(int userId) async {
    List<Map<String, dynamic>> visits = [];
    try {
      if (_dbHelper != null) {
        // 使用通用查询方法替代未定义的getUpcomingPrenatalVisits方法
        visits = await _dbHelper!.queryRows('prenatal_visits', 
          where: {'user_id': userId, 'visit_date > ?': [DateTime.now().millisecondsSinceEpoch]});
      }
    } catch (e) {
      // 记录错误但不使用print
    }
    if (visits.isNotEmpty) {
      return PrenatalVisit.fromMap(visits.first);
    }
    return null;
  }

  // 记录孕期症状
  Future<PregnancySymptom> recordSymptom({
    required int userId,
    required DateTime date,
    required String symptomName,
    required int severity,
    required String description,
    String? notes,
  }) async {
    final symptom = PregnancySymptom(
      userId: userId,
      date: date,
      symptomName: symptomName,
      severity: severity,
      description: description,
      notes: notes,
    );

    final id = await _dbHelper?.insert('pregnancy_symptoms', symptom.toMap());
    
    // 检查是否需要提醒用户（严重症状）
    // if (severity >= 4) {
    //     // await _checkAndNotifyCriticalSymptom(userId, symptom);
    //   }
    
    return symptom.copyWith(id: id);
  }

  // 获取症状历史
  Future<List<PregnancySymptom>> getSymptoms(
      int userId, {DateTime? startDate, DateTime? endDate}) async {
    List<Map<String, dynamic>> symptoms = [];
    try {
      if (_dbHelper != null) {
        // 使用通用查询方法替代未定义的getPregnancySymptoms方法
        symptoms = await _dbHelper!.queryRows('pregnancy_symptoms', 
          where: {'user_id': userId});
      }
    } catch (e) {
      // 记录错误但不使用print
    }
    return symptoms.map((map) => PregnancySymptom.fromMap(map)).toList();
  }

  // 获取症状统计
  Future<Map<String, dynamic>> getSymptomStatistics(int userId) async {
    final allSymptoms = await getSymptoms(userId);
    
    // 统计最常见的症状
    final symptomCounts = <String, int>{};
    final severityBySymptom = <String, List<int>>{};
    
    for (var symptom in allSymptoms) {
      symptomCounts[symptom.symptomName] = (symptomCounts[symptom.symptomName] ?? 0) + 1;
      
      if (!severityBySymptom.containsKey(symptom.symptomName)) {
        severityBySymptom[symptom.symptomName] = [];
      }
      severityBySymptom[symptom.symptomName]!.add(symptom.severity);
    }
    
    // 按频率排序
    final sortedSymptoms = symptomCounts.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));
    
    // 计算平均严重程度
    final avgSeverityBySymptom = <String, double>{};
    severityBySymptom.forEach((symptom, severities) {
      final avg = severities.reduce((a, b) => a + b) / severities.length;
      avgSeverityBySymptom[symptom] = avg;
    });
    
    return {
      'total_symptoms': allSymptoms.length,
      'most_common_symptoms': sortedSymptoms.take(5).map((e) => e.key).toList(),
      'symptom_frequency': symptomCounts,
      'average_severity': avgSeverityBySymptom,
    };
  }

  // 查询食物安全性
  Future<List<FoodSafetyInfo>> searchFoodSafety(String query) async {
    List<Map<String, dynamic>> foods = [];
    try {
      if (_dbHelper != null) {
        // 使用通用查询方法替代未定义的searchFoodSafety方法
        foods = await _dbHelper!.queryRows('food_safety_info', 
          where: {'food_name LIKE ?': ['%$query%']});
      }
    } catch (e) {
      // 记录错误但不使用print
    }
    return foods.map((map) => FoodSafetyInfo.fromMap(map)).toList();
  }

  // 获取食物分类列表
  Future<List<String>> getFoodCategories() async {
    return foodCategories;
  }

  // 按分类获取食物
  Future<List<FoodSafetyInfo>> getFoodsByCategory(String category) async {
    List<Map<String, dynamic>> foods = [];
    try {
      if (_dbHelper != null) {
        // 使用通用查询方法替代未定义的getFoodsByCategory方法
        foods = await _dbHelper!.queryRows('food_safety_info', 
          where: {'category': category});
      }
    } catch (e) {
      // 记录错误但不使用print
    }
    return foods.map((map) => FoodSafetyInfo.fromMap(map)).toList();
  }

  // 记录胎动
  Future<FetalMovementRecord> recordFetalMovement({
    required int userId,
    required DateTime date,
    required String time,
    required int movementCount,
    required String movementType,
    String? notes,
  }) async {
    final record = FetalMovementRecord(
      userId: userId,
      date: date,
      time: time,
      movementCount: movementCount,
      movementType: movementType,
      notes: notes,
    );

    final id = await _dbHelper?.insert('fetal_movements', record.toMap());
    
    // 分析胎动模式
    // await _analyzeFetalMovementPattern(userId);
    
    return record.copyWith(id: id);
  }

  // 获取胎动记录
  Future<List<FetalMovementRecord>> getFetalMovements(
      int userId, {DateTime? startDate, DateTime? endDate}) async {
    List<Map<String, dynamic>> records = [];
    try {
      if (_dbHelper != null) {
        // 使用通用查询方法替代未定义的getFetalMovements方法
        records = await _dbHelper!.queryRows('fetal_movements', 
          where: {'user_id': userId});
      }
    } catch (e) {
      // 记录错误但不使用print
    }
    return records.map((map) => FetalMovementRecord.fromMap(map)).toList();
  }

  // 记录孕期健康数据
  Future<PregnancyHealthData> recordHealthData({
    required int userId,
    required DateTime date,
    required double weight,
    String? bloodPressure,
    int? heartRate,
    String? glucoseLevel,
    String? sleepHours,
    String? activityLevel,
    String? notes,
  }) async {
    final healthData = PregnancyHealthData(
      userId: userId,
      date: date,
      weight: weight,
      bloodPressure: bloodPressure,
      heartRate: heartRate,
      glucoseLevel: glucoseLevel,
      sleepHours: sleepHours,
      activityLevel: activityLevel,
      notes: notes,
    );

    final id = await _dbHelper?.insert('pregnancy_health_data', healthData.toMap());
    
    // 分析体重增长趋势
    // await _analyzeWeightGainTrend(userId);
    
    return healthData.copyWith(id: id);
  }

  // 获取健康数据趋势
  Future<List<PregnancyHealthData>> getHealthDataTrend(int userId, int days) async {
      // 移除未使用的变量
      // final endDate = DateTime.now();
      // final startDate = endDate.subtract(Duration(days: days));
      
      List<Map<String, dynamic>> records = [];
      try {
          if (_dbHelper != null) {
              // 使用通用查询方法替代可能未定义的特定方法
              records = await _dbHelper!.queryRows('pregnancy_health_data', 
                where: {'user_id': userId});
            }
          } catch (e) {
            // 记录错误但不使用print
          }
    
    // 按日期排序
    final sortedRecords = records.map((map) => PregnancyHealthData.fromMap(map))
      .toList()..sort((a, b) => a.date.compareTo(b.date));
    
    return sortedRecords;
  }

  // 获取孕期里程碑
  Future<List<PregnancyMilestone>> getMilestones(int currentWeek, int lookAheadWeeks) async {
    final milestones = <PregnancyMilestone>[];
    
    // 获取当前周及未来几周的里程碑
    try {
      for (int i = 0; i <= lookAheadWeeks; i++) {
        final week = currentWeek + i;
        List<Map<String, dynamic>> weekMilestones = [];
        
        if (_dbHelper != null) {
            // 使用通用查询方法替代可能未定义的特定方法
            final results = await _dbHelper!.queryRows('milestones', where: {'week': week});
            weekMilestones = results;
          }
        
        for (var milestoneMap in weekMilestones) {
          milestones.add(PregnancyMilestone.fromMap(milestoneMap));
        }
      }
    } catch (e) {
      // 处理异常，返回已收集的里程碑
    }
    
    // 如果数据库中没有里程碑，生成默认的
    if (milestones.isEmpty) {
      await _loadDefaultMilestones();
      return getMilestones(currentWeek, lookAheadWeeks);
    }
    
    return milestones;
  }

  // 注释掉未使用的方法（DatabaseHelper类中没有createReminder方法）
  // Future<void> createPrenatalReminder({
  //   required int userId,
  //   required DateTime visitDate,
  //   required String doctorName,
  //   required String hospitalName,
  //   String? notes,
  // }) async {
  //   // 计算提醒时间（提前1天、3天和1周）
  //   final reminders = [
  //     visitDate.subtract(Duration(days: 7)),
  //     visitDate.subtract(Duration(days: 3)),
  //     visitDate.subtract(Duration(days: 1)),
  //   ];
  //
  //   // 创建提醒
  //   for (var reminderDate in reminders) {
  //     if (reminderDate.isAfter(DateTime.now())) {
  //       if (_dbHelper != null) {
  //         // await _dbHelper.createReminder(
  //         //   userId: userId,
  //         //   title: '产检提醒',
  //         //   description: '您预约了${DateFormat('yyyy-MM-dd').format(visitDate)}在$hospitalName与$doctorName医生的产检。',
  //         //   reminderDate: reminderDate,
  //         //   type: 'prenatal_visit',
  //         // );
  //       }
  //     }
  //   }
  // }
  // 获取孕期建议
  Future<String> getWeeklyAdvice(int week) async {
    // 基于孕周提供不同的建议
    switch (week) {
      case <= 12:
        return '孕早期是胎儿发育的关键时期，建议您保持良好的作息，避免接触有害物质，补充叶酸，并注意观察是否有异常出血或剧烈腹痛。';
      case <= 28:
        return '孕中期是相对舒适的阶段，您可能会感受到胎动。建议适当运动，均衡饮食，控制体重增长，并开始进行胎教。';
      case <= 40:
        return '孕晚期需要密切关注胎动情况，每周进行产检。准备好待产包，学习分娩知识和哺乳技巧，适当活动以帮助顺产。';
      default:
        return '恭喜您已到预产期！请随时准备分娩，注意观察宫缩、见红和破水等分娩征兆，如有异常及时就医。';
    }
  }

  // 私有辅助方法

  // 加载默认的胎儿发育数据
  Future<void> _loadDefaultFetalDevelopmentData() async {
    try {
      // 使用try-catch处理可能的未定义方法调用
      if (_dbHelper != null) {
          // 使用通用查询方法替代可能未定义的特定方法
          final countResults = await _dbHelper!.queryRows('fetal_development');
          if (countResults.isNotEmpty) return; // 已存在数据，不需要加载
        }
    } catch (e) {
      // 发生异常时继续执行，尝试插入默认数据
    }

    // 创建一些默认的胎儿发育数据
    final defaultDevelopments = [
      FetalDevelopment(
        week: 1,
        sizeDescription: '像一粒芝麻',
        weightDescription: '约0.0005克',
        sizeInCm: 0.1,
        weightInGrams: 0.0005,
        keyDevelopments: [
          '受精卵形成并开始分裂',
          '开始向子宫移动',
          '准备着床'
        ],
        commonSymptoms: '此时通常没有明显症状',
        recommendations: '保持健康生活方式，避免吸烟饮酒',
        imageAssetName: 'fetus_week1',
        comparisonDescription: '芝麻大小',
      ),
      FetalDevelopment(
        week: 4,
        sizeDescription: '像一颗罂粟种子',
        weightDescription: '约0.04克',
        sizeInCm: 0.4,
        weightInGrams: 0.04,
        keyDevelopments: [
          '胚胎形成三个胚层',
          '神经系统开始发育',
          '心脏开始形成'
        ],
        commonSymptoms: '可能出现轻微恶心、乳房胀痛',
        recommendations: '继续补充叶酸，避免剧烈运动',
        imageAssetName: 'fetus_week4',
        comparisonDescription: '罂粟种子大小',
      ),
      FetalDevelopment(
        week: 8,
        sizeDescription: '像一颗芸豆',
        weightDescription: '约2克',
        sizeInCm: 2.0,
        weightInGrams: 2.0,
        keyDevelopments: [
          '所有主要器官开始形成',
          '面部特征逐渐明显',
          '心脏开始跳动',
          '手臂和腿部开始发育'
        ],
        commonSymptoms: '恶心呕吐、疲劳、尿频',
        recommendations: '少量多餐，保证充分休息',
        imageAssetName: 'fetus_week8',
        comparisonDescription: '芸豆大小',
      ),
      FetalDevelopment(
        week: 12,
        sizeDescription: '像一个李子',
        weightDescription: '约14克',
        sizeInCm: 6.0,
        weightInGrams: 14.0,
        keyDevelopments: [
          '手指和脚趾完全分开',
          '可以握拳',
          '外生殖器开始发育',
          '骨骼开始硬化'
        ],
        commonSymptoms: '孕吐可能减轻，食欲增加',
        recommendations: '均衡饮食，开始适当运动',
        imageAssetName: 'fetus_week12',
        comparisonDescription: '李子大小',
      ),
      FetalDevelopment(
        week: 20,
        sizeDescription: '像一个香蕉',
        weightDescription: '约300克',
        sizeInCm: 16.0,
        weightInGrams: 300.0,
        keyDevelopments: [
          '可以听到外界声音',
          '开始有规律性的胎动',
          '头发开始生长',
          '指甲完全形成'
        ],
        commonSymptoms: '胎动、腿抽筋、背痛',
        recommendations: '补充钙质，注意胎动规律',
        imageAssetName: 'fetus_week20',
        comparisonDescription: '香蕉大小',
      ),
      FetalDevelopment(
        week: 28,
        sizeDescription: '像一个菜花',
        weightDescription: '约1000克',
        sizeInCm: 25.0,
        weightInGrams: 1000.0,
        keyDevelopments: [
          '眼睛可以睁开和闭合',
          '肺部开始发育',
          '开始有规律的睡眠周期',
          '皮下脂肪开始积累'
        ],
        commonSymptoms: '呼吸不畅、水肿、疲劳',
        recommendations: '左侧卧位，避免长时间站立',
        imageAssetName: 'fetus_week28',
        comparisonDescription: '菜花大小',
      ),
      FetalDevelopment(
        week: 36,
        sizeDescription: '像一个小西瓜',
        weightDescription: '约2700克',
        sizeInCm: 45.0,
        weightInGrams: 2700.0,
        keyDevelopments: [
          '肺部基本发育成熟',
          '胎位基本固定',
          '皮下脂肪继续增加',
          '指甲超过指尖'
        ],
        commonSymptoms: '频繁宫缩、尿频加重、腰酸背痛',
        recommendations: '每周产检，准备待产包',
        imageAssetName: 'fetus_week36',
        comparisonDescription: '小西瓜大小',
      ),
      FetalDevelopment(
        week: 40,
        sizeDescription: '像一个大西瓜',
        weightDescription: '约3500-4000克',
        sizeInCm: 50.0,
        weightInGrams: 3750.0,
        keyDevelopments: [
          '完全准备好出生',
          '所有器官发育成熟',
          '头部进入骨盆',
          '皮肤光滑饱满'
        ],
        commonSymptoms: '宫缩频繁、见红、破水',
        recommendations: '随时准备分娩，注意分娩征兆',
        imageAssetName: 'fetus_week40',
        comparisonDescription: '大西瓜大小',
      ),
    ];

    // 插入默认数据
    for (var development in defaultDevelopments) {
      try {
        if (_dbHelper != null) {
          // 使用通用插入方法替代可能未定义的特定方法
          await _dbHelper!.insert('fetal_development', development.toMap());
        }
      } catch (e) {
        // 处理单个插入失败
        continue;
      }
    }
  }

  // 加载默认的食物安全数据
  Future<void> _loadDefaultFoodSafetyData() async {
    try {
      // 使用try-catch处理可能的未定义方法调用
      if (_dbHelper != null) {
          // 使用通用查询方法替代可能未定义的特定方法
          final countResults = await _dbHelper!.queryRows('food_safety_info');
          if (countResults.isNotEmpty) return; // 已存在数据，不需要加载
        }
    } catch (e) {
      // 发生异常时继续执行，尝试插入默认数据
    }

    // 创建一些默认的食物安全数据
    final defaultFoods = [
      FoodSafetyInfo(
        id: 1,
        foodName: '苹果',
        safetyStatus: 'safe',
        category: '水果',
        description: '富含维生素和纤维素',
        safetyExplanation: '苹果是孕期非常安全和健康的水果，含有丰富的维生素C和纤维素，有助于缓解便秘。',
        alternatives: ['香蕉', '梨', '橙子'],
      ),
      FoodSafetyInfo(
        id: 2,
        foodName: '生鱼片',
        safetyStatus: 'unsafe',
        category: '海鲜',
        description: '生的鱼肉制品',
        safetyExplanation: '生鱼片可能含有寄生虫和细菌，如沙门氏菌、李斯特菌等，对孕妇和胎儿有潜在风险。',
        alternatives: ['熟透的烤鱼', '蒸虾', '煮蟹'],
      ),
      FoodSafetyInfo(
        id: 3,
        foodName: '咖啡',
        safetyStatus: 'caution',
        category: '饮料',
        description: '含咖啡因的饮料',
        safetyExplanation: '孕期应限制咖啡因摄入，每天不超过200毫克（约1-2杯咖啡）。过量咖啡因可能增加流产风险。',
        alternatives: ['无咖啡因咖啡', '花草茶', '果汁'],
        preparationNotes: '选择低咖啡因或无咖啡因版本',
      ),
      FoodSafetyInfo(
        id: 4,
        foodName: '菠菜',
        safetyStatus: 'safe',
        category: '蔬菜',
        description: '绿叶蔬菜',
        safetyExplanation: '菠菜富含叶酸、铁和钙，对孕妇和胎儿都有益。但应彻底清洗以去除可能的农药残留。',
        alternatives: ['羽衣甘蓝', '西兰花', '油菜'],
      ),
      FoodSafetyInfo(
        id: 5,
        foodName: '寿司',
        safetyStatus: 'caution',
        category: '其他',
        description: '日本传统食品',
        safetyExplanation: '含有生鱼的寿司应避免食用，但可以选择全熟或素食寿司。确保米饭新鲜，避免食物中毒。',
        alternatives: ['熟寿司', '素食寿司', '手卷'],
        preparationNotes: '只选择使用完全煮熟食材的寿司',
      ),
      FoodSafetyInfo(
        id: 6,
        foodName: '牛奶',
        safetyStatus: 'safe',
        category: '乳制品',
        description: '富含钙和蛋白质',
        safetyExplanation: '牛奶是孕期优质的钙和蛋白质来源，有助于胎儿骨骼发育。确保选择经过巴氏消毒的牛奶。',
        alternatives: ['酸奶', '奶酪', '豆浆'],
      ),
      FoodSafetyInfo(
        id: 7,
        foodName: '热狗',
        safetyStatus: 'caution',
        category: '肉类',
        description: '加工肉制品',
        safetyExplanation: '热狗等加工肉制品可能含有亚硝酸盐和防腐剂，应彻底加热后食用。',
        alternatives: ['新鲜鸡肉', '牛肉', '鱼肉'],
        preparationNotes: '必须彻底加热至内部温度达到75°C以上',
      ),
      FoodSafetyInfo(
        id: 8,
        foodName: '肝脏',
        safetyStatus: 'caution',
        category: '肉类',
        description: '动物内脏',
        safetyExplanation: '肝脏富含维生素A，但过量摄入可能对胎儿有害。孕期应适量食用，每周不超过100克。',
        alternatives: ['瘦肉', '鸡蛋', '豆类'],
      ),
      FoodSafetyInfo(
        id: 9,
        foodName: '杏仁',
        safetyStatus: 'safe',
        category: '坚果',
        description: '富含蛋白质和健康脂肪',
        safetyExplanation: '杏仁是孕期健康的零食选择，富含蛋白质、纤维和健康脂肪。但应适量食用，避免过敏。',
        alternatives: ['核桃', '腰果', '南瓜籽'],
      ),
      FoodSafetyInfo(
        id: 10,
        foodName: '未熟透的肉类',
        safetyStatus: 'unsafe',
        category: '肉类',
        description: '未完全煮熟的肉',
        safetyExplanation: '未熟透的肉类可能含有弓形虫、沙门氏菌等病原体，对孕妇和胎儿构成严重风险。',
        alternatives: ['完全熟透的肉类', '豆腐', '豆类'],
        preparationNotes: '确保肉类内部温度达到75°C以上',
      ),
    ];

    // 插入默认数据
    for (var food in defaultFoods) {
      try {
        if (_dbHelper != null) {
          // 使用通用插入方法替代可能未定义的特定方法
          await _dbHelper!.insert('food_safety_info', food.toMap());
        }
      } catch (e) {
        // 处理单个插入失败
        continue;
      }
    }
  }

  // 加载默认的孕期里程碑
  Future<void> _loadDefaultMilestones() async {
    try {
      // 使用try-catch处理可能的未定义方法调用
      if (_dbHelper != null) {
          // 使用通用查询方法替代可能未定义的特定方法
          final countResults = await _dbHelper!.queryRows('milestones');
          if (countResults.isNotEmpty) return; // 已存在数据，不需要加载
        }
    } catch (e) {
      // 发生异常时继续执行，尝试插入默认数据
    }

    // 创建一些默认的孕期里程碑
    final defaultMilestones = [
      PregnancyMilestone(
        id: 1,
        week: 4,
        title: '确认怀孕',
        description: '通过妊娠试纸或血液检查确认怀孕',
        thingsToKnow: [
          '可能会出现月经推迟、恶心、乳房胀痛等症状',
          '建议尽早咨询医生进行产前检查',
          '开始补充叶酸和其他必要营养素'
        ],
        imageAssetName: 'milestone_week4',
      ),
      PregnancyMilestone(
        id: 2,
        week: 8,
        title: '第一次产检',
        description: '进行第一次正式产检，确认胎儿发育情况',
        thingsToKnow: [
          '医生可能会进行超声波检查',
          '了解基础血压、体重等健康指标',
          '讨论孕期注意事项和饮食建议'
        ],
        imageAssetName: 'milestone_week8',
      ),
      PregnancyMilestone(
        id: 3,
        week: 12,
        title: 'NT检查',
        description: '进行颈项透明层检查，评估胎儿染色体异常风险',
        thingsToKnow: [
          '这是一项重要的筛查检查',
          '检查时间通常在11-13周+6天',
          '可结合血液检查提高筛查准确性'
        ],
        imageAssetName: 'milestone_week12',
      ),
      PregnancyMilestone(
        id: 4,
        week: 20,
        title: '感觉到胎动',
        description: '大多数孕妇在这个时期开始感觉到明显的胎动',
        thingsToKnow: [
          '胎动感觉像是蝴蝶振翅或小鱼游动',
          '开始记录胎动规律',
          '注意观察胎动次数和强度变化'
        ],
        imageAssetName: 'milestone_week20',
      ),
      PregnancyMilestone(
        id: 5,
        week: 24,
        title: '四维彩超',
        description: '进行详细的胎儿结构检查',
        thingsToKnow: [
          '可以更清晰地看到胎儿的面部和身体结构',
          '检查胎儿是否有明显的畸形',
          '可能会获得胎儿的照片作为纪念'
        ],
        imageAssetName: 'milestone_week24',
      ),
      PregnancyMilestone(
        id: 6,
        week: 28,
        title: '进入孕晚期',
        description: '开始进入孕期的最后三个月',
        thingsToKnow: [
          '需要增加产检频率（每两周一次）',
          '注意监测血压和血糖',
          '开始准备待产包和婴儿用品'
        ],
        imageAssetName: 'milestone_week28',
      ),
      PregnancyMilestone(
        id: 7,
        week: 32,
        title: '胎位检查',
        description: '检查胎儿的胎位是否正常',
        thingsToKnow: [
          '正常胎位为头位（头部朝下）',
          '如果是臀位，医生可能建议胸膝卧位纠正',
          '36周后胎位基本固定'
        ],
        imageAssetName: 'milestone_week32',
      ),
      PregnancyMilestone(
        id: 8,
        week: 36,
        title: '每周产检',
        description: '开始每周进行一次产检',
        thingsToKnow: [
          '检查胎儿心率和胎位',
          '评估宫颈成熟度',
          '讨论分娩方式和注意事项'
        ],
        imageAssetName: 'milestone_week36',
      ),
      PregnancyMilestone(
        id: 9,
        week: 38,
        title: '胎儿足月',
        description: '胎儿已经足月，随时可能出生',
        thingsToKnow: [
          '密切关注分娩征兆',
          '准备好随时前往医院',
          '保持良好休息，保存体力'
        ],
        imageAssetName: 'milestone_week38',
      ),
      PregnancyMilestone(
        id: 10,
        week: 40,
        title: '预产期',
        description: '理论上的分娩日期',
        thingsToKnow: [
          '只有约5%的婴儿在预产期当天出生',
          '超过预产期1周仍未分娩，医生可能会建议引产',
          '继续密切监测胎儿情况'
        ],
        imageAssetName: 'milestone_week40',
      ),
    ];

    // 插入默认数据
    for (var milestone in defaultMilestones) {
      try {
        if (_dbHelper != null) {
          // 使用通用插入方法替代可能未定义的特定方法
          await _dbHelper!.insert('milestones', milestone.toMap());
        }
      } catch (e) {
        // 处理单个插入失败
        continue;
      }
    }
  }

  // 生成默认的胎儿发育信息
  FetalDevelopment _generateDefaultFetalDevelopment(int week) {
    // 基于孕周估算胎儿大小和体重
    double sizeInCm;
    double weightInGrams;
    String sizeDescription;
    String weightDescription;
    String comparisonDescription;
    
    if (week <= 12) {
      sizeInCm = week * 0.5;
      weightInGrams = pow(week, 3) * 0.05;
      sizeDescription = '像一颗小种子';
      weightDescription = '非常轻';
      comparisonDescription = '种子大小';
    } else if (week <= 24) {
      sizeInCm = week * 0.8;
      weightInGrams = pow(week, 2.5) * 2;
      sizeDescription = '像一个中等大小的水果';
      weightDescription = '约几百克';
      comparisonDescription = '水果大小';
    } else if (week <= 36) {
      sizeInCm = 25 + (week - 24) * 2;
      weightInGrams = 1000 + (week - 24) * 150;
      sizeDescription = '像一个大蔬菜';
      weightDescription = '约几公斤';
      comparisonDescription = '蔬菜大小';
    } else {
      sizeInCm = 50 + (week - 36) * 1;
      weightInGrams = 3000 + (week - 36) * 200;
      sizeDescription = '像一个西瓜';
      weightDescription = '约3-4公斤';
      comparisonDescription = '西瓜大小';
    }

    return FetalDevelopment(
      week: week,
      sizeDescription: sizeDescription,
      weightDescription: weightDescription,
      sizeInCm: sizeInCm,
      weightInGrams: weightInGrams,
      keyDevelopments: [
        '胎儿继续生长发育',
        '器官功能逐渐完善',
        '身体比例更加协调'
      ],
      commonSymptoms: '孕期正常症状持续',
      recommendations: '继续规律产检，保持健康生活方式',
      imageAssetName: 'fetus_week$week',
      comparisonDescription: comparisonDescription,
    );
  }

  // 注释掉未使用的方法（DatabaseHelper类中没有createReminder方法）
  // Future<void> _createNextVisitReminder(int userId, DateTime visitDate, String doctorName, String hospitalName) async {
  //   // 计算提醒时间（提前1天和3天）
  //   final reminders = [
  //     visitDate.subtract(Duration(days: 3)),
  //     visitDate.subtract(Duration(days: 1)),
  //   ];
  //
  //   for (var reminderDate in reminders) {
  //     if (reminderDate.isAfter(DateTime.now())) {
  //       if (_dbHelper != null) {
  //         // await _dbHelper.createReminder(
  //         //   userId: userId,
  //         //   title: '产检提醒',
  //         //   description: '您预约了${DateFormat('yyyy-MM-dd').format(visitDate)}在$hospitalName与$doctorName医生的产检。',
  //         //   reminderDate: reminderDate,
  //         //   type: 'prenatal_visit',
  //         // );
  //       }
  //     }
  //   }
  // }

  // 注释掉未使用的方法（DatabaseHelper类中没有createReminder方法）
  // Future<void> _checkAndNotifyCriticalSymptom(int userId, PregnancySymptom symptom) async {
  //   // 记录严重症状提醒
  //   if (_dbHelper != null) {
  //     // await _dbHelper!.createReminder(
  //     //   userId: userId,
  //     //   title: '严重症状提醒',
  //     //   description: '您记录了严重程度为${symptom.severityDescription}的${symptom.symptomName}症状，建议及时咨询医生。',
  //     //   reminderDate: DateTime.now(),
  //     //   type: 'critical_symptom',
  //     // );
  //   }
  // }

  // 注释掉未使用的方法（DatabaseHelper类中没有createReminder方法）
  // Future<void> _analyzeFetalMovementPattern(int userId) async {
  //   final last7DaysRecords = await getFetalMovements(
  //     userId,
  //     startDate: DateTime.now().subtract(Duration(days: 7)),
  //   );
  //
  //   if (last7DaysRecords.length >= 5) {
  //     // 计算平均每日胎动次数
  //     final dailyCounts = <DateTime, int>{};
  //     
  //     for (var record in last7DaysRecords) {
  //       final dateKey = DateTime(record.date.year, record.date.month, record.date.day);
  //       dailyCounts[dateKey] = (dailyCounts[dateKey] ?? 0) + record.movementCount;
  //     }
  //
  //     if (dailyCounts.length >= 3) {
  //       final counts = dailyCounts.values.toList();
  //       final avgCount = counts.reduce((a, b) => a + b) / counts.length;
  //       
  //       // 如果最新记录的胎动次数明显低于平均值（低于50%），创建提醒
  //       final latestDate = dailyCounts.keys.reduce((a, b) => a.isAfter(b) ? a : b);
  //       final latestCount = dailyCounts[latestDate]!;
  //       
  //       if (latestCount < avgCount * 0.5 && _dbHelper != null) {
  //         // await _dbHelper!.createReminder(
  //         //   userId: userId,
  //         //   title: '胎动减少提醒',
  //         //   description: '今日胎动次数明显少于近期平均水平，建议密切关注。如持续减少，请及时就医。',
  //         //   reminderDate: DateTime.now(),
  //         //   type: 'fetal_movement_concern',
  //         // );
  //       }
  //     }
  //   }
  // }

  // 注释掉未使用的方法（DatabaseHelper类中没有createReminder方法）
  // Future<void> _analyzeWeightGainTrend(int userId) async {
  //   final healthData = await getHealthDataTrend(userId, 30);
  //   
  //   if (healthData.length >= 3) {
  //     // 计算每周体重增长
  //     final weeklyGains = <double>[];
  //     
  //     for (int i = 7; i < healthData.length; i++) {
  //       final currentWeight = healthData[i].weight;
  //       final weekAgoWeight = healthData[i - 7].weight;
  //       weeklyGains.add(currentWeight - weekAgoWeight);
  //     }
  //
  //     if (weeklyGains.isNotEmpty) {
  //       final avgWeeklyGain = weeklyGains.reduce((a, b) => a + b) / weeklyGains.length;
  //       
  //       // 根据孕期阶段评估体重增长是否合理
  //       final pregnancyInfo = await getPregnancyInfo(userId);
  //       if (pregnancyInfo != null) {
  //         double recommendedMaxGain = 0.5; // 千克/周
  //         
  //         if (pregnancyInfo.currentWeek! <= 20) {
  //           recommendedMaxGain = 0.25;
  //         } else if (pregnancyInfo.currentWeek! <= 30) {
  //           recommendedMaxGain = 0.4;
  //         } else {
  //           recommendedMaxGain = 0.5;
  //         }
  //
  //         // 如果体重增长过快，创建提醒
  //           if (avgWeeklyGain > recommendedMaxGain * 1.5 && _dbHelper != null) {
  //             // await _dbHelper!.createReminder(
  //             //   userId: userId,
  //             //   title: '体重增长过快提醒',
  //             //   description: '您的体重增长速度较快，建议咨询医生或营养师，调整饮食和运动计划。',
  //             //   reminderDate: DateTime.now(),
  //             //   type: 'weight_gain_concern',
  //             // );
  //           }
  //         }
  //       }
  //     }
  //   }
  // }
}